<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "admin".
 *
 * @property int $id
 * @property string $username 用户名
 * @property string $password 密码
 * @property int $status 状态
 * @property int $created_at 创建时间
 */
class Admin extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'admin';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['status', 'created_at'], 'integer'],
            [['name', 'username', 'password', 'icon'], 'string', 'max' => 255]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'username' => 'Username',
            'password' => 'Password',
            'icon' => 'Icon',
            'status' => 'Status',
            'created_at' => 'Created At',
        ];
    }

    public function removeTokens(){
        UserLogin::deleteAll(
            'user_id = :user_id and token != :token',
            [':user_id'=>$this->id, ':token'=>$this->getBearToken()]
        );
    }

    private function getBearToken(){
        $authHeader = Yii::$app->getRequest()->getHeaders()->get('Authorization');
        if (preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
            return $matches[1];
        } else {
            return null;
        }
    }
}
